<template>
	<view class="kui-radio-group kui-w-full kui-h-full kui-flex kui-items-center" :style="rootStyle">
		<slot></slot>
	</view>
</template>

<script lang="ts">
	import {
		reactive,
		defineComponent,
		provide,
		nextTick,
		onMounted,
		CSSProperties,
		computed
	} from 'vue';
	
	import RadioGroupProps from './props';
	
	const name = 'kui-radio-group';
	
	export default defineComponent({
		name,
		props: RadioGroupProps,
		emits: ['change'],
		setup(props, { emit }) {
			const rootStyle = computed(() => {
				const style: CSSProperties = reactive({});
				
				style.flexDirection = props.direction;
				
				console.log(props.direction);
				
				return style;
			})
			
			const childrens = reactive([]);
			
			const init = () => {
				nextTick(() => {
					if (childrens) {
						childrens.forEach((vm, index) => {
							if (props.direction === 'row') {
								vm.marginRight = '40rpx';
							}
							if (index !== childrens.length-1 && props.direction === 'column') {
								vm.marginBottom = '30rpx';
							}
							if (vm.value && props.modelValue === vm.value) {
								vm.checked = true;
							}
						})
					}
				})
			}
			
			const changeRadio = (item) => {
				if (childrens) {
					childrens.forEach((vm, index) => {
						if (item.id !== vm.id) {
							vm.checked = false;
						}
					})
				}
			}
			
			// 监听子组件点击事件
			const onChange = (e) => {
				changeRadio(e);
				emit('change', e.value);
			}
			
			onMounted(() => {
				init();
			})
			
			provide('radio-group', {
				childrens,
				onChange,
				...props
			})
			
			return {
				rootStyle,
				childrens
			}
		}
	});
</script>

<style>

</style>